<?php
declare (strict_types=1);

namespace app\store\model\store;

use app\common\model\store\User as StoreUserModel;
use app\common\service\store\User as StoreUserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\Paginator;

/**
 * 机构用户模型
 * Class StoreUser
 * @package app\store\model
 */
class User extends StoreUserModel
{
    /**
     * 隐藏的字段
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    // 用户登录token
    private $token;

    /**
     * 机构用户登录
     * @param array $data
     * @return array|bool|null|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(array $data)
    {
        // 验证用户名密码是否正确
        if (!$userInfo = $this->getUserInfoByLogin($data)) {
            return false;
        }
        // 验证平台状态是否正常
        if (empty($userInfo['store']) || $userInfo['store']['is_delete']) {
            $this->error = '登录失败, 未找到当前平台信息';
            return false;
        }
        if ($userInfo['store']['is_recycle']) {
            $this->error = '登录失败, 当前平台已删除';
            return false;
        }

        // 记录此次登录时间
        $userInfo->update_time = time();
        $userInfo->save();

        // 记录登录状态, 并记录token
        $this->token = StoreUserService::login($userInfo->toArray());
        return $userInfo;
    }

    /**
     * 获取登录用户信息
     * @param array $data
     * @return array|bool|null|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getUserInfoByLogin(array $data)
    {
        // 用户信息
        $useInfo = static::withoutGlobalScope()
            ->with(['store'])
            ->where('phone', '=', trim($data['phone']))
            ->where('is_delete', '=', 0)
            ->find();
        if (empty($useInfo) || $useInfo['is_delete']) {
            $this->error = '登录失败, 该用户不存在或已删除';
            return false;
        }
        // 验证密码是否正确
        if (!password_verify($data['password'], $useInfo['password'])) {
            $this->error = '登录失败, 用户名或密码错误';
            return false;
        }
        return $useInfo;
    }

    /**
     * 返回生成的token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * 获取用户列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $params = $this->setQueryDefaultValue($param, [
            'real_name' => '',
            'phone' => '',
            'status' => '',
            'create_time' => '',
            'update_time' => '',
            'parent_store_user_id' => null
        ]);

        $filter = [];

        // 关键词搜索
        !empty($params['real_name']) && $filter[] = ['real_name', 'like', "%{$params['real_name']}%"];
        !empty($params['phone']) && $filter[] = ['phone', 'like', "%{$params['phone']}%"];
        $params['status'] !== '' && $filter[] = ['status', '=', $params['status']];

        !empty($params['parent_store_user_id']) && $query->where('parent_store_user_id', 'in', $params['parent_store_user_id']);


        $order = [
            'create_time' => 'desc',
        ];
        if (!empty($params['create_time']) && is_array($params['create_time'])) {
            $times = between_time($params['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        } else if (!empty($params['create_time'])) {
            $order['create_time'] = $params['create_time'];
        }

        if (!empty($params['update_time']) && is_array($params['update_time'])) {
            $times = between_time($params['update_time']);
            $filter[] = ['update_time', '>=', $times['start_time']];
            $filter[] = ['update_time', '<', $times['end_time'] + 86400];
        } else if (!empty($params['update_time'])) {
            $order['update_time'] = $params['update_time'];
        }

        // 查询列表记录
        $list = $query
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order($order)
            ->paginate(15);

        foreach ($list as &$v) {
            $v['roleIds'] = [];
            $children = $this->getChildrenUserList($v['store_user_id']);
            if (count($children) > 0) {
                $v['children'] = $children;
            }
            $v['children_count'] = $this->getChildrenUserCount($v['store_user_id']);
        }
        return $list;
    }

    public function getChildrenUserList($store_user_id)
    {
        $where = [
            'parent_store_user_id' => $store_user_id,
            'is_delete' => 0,
        ];
        $cuser = $this->where($where)->select();
        foreach ($cuser as $v) {
            $v->roleIds = [];
            $children = $this->getChildrenUserList($v->store_user_id);
            if (count($children) > 0) {
                $v->children = $children;
            }
            $v->children_count = $this->getChildrenUserCount($v->store_user_id);
        }
        return $cuser;
    }

    public function getChildrenUserCount($store_user_id)
    {
        $where = [
            'parent_store_user_id' => $store_user_id,
            'is_delete' => 0,
        ];
        return $this->where($where)->count();
    }

    /**
     * 新增记录
     * @param array $data
     * @return bool
     */
    public function add(array $data)
    {
//        $data['user_name'] = strtolower($data['user_name']);
//        if (self::checkExist($data['user_name'])) {
//            $this->error = '用户名已存在';
//            return false;
//        }

        if (self::checkPhoneExist($data['phone'])) {
            $this->error = '手机号码已存在，请换一个重试！';
            return false;
        }
        if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }

        // 整理数据
        $data['password'] = encryption_hash($data['password']);
        $data['store_id'] = self::$storeId;
        $data['is_super'] = 0;
        $data['roles'] = [10004];
        $data['h5_code_time'] = time();

        // 事务处理
        $this->transaction(function () use ($data) {
            // 新增用户记录
            $this->save($data);
            // 新增角色关系记录
            UserRole::increased((int)$this['store_user_id'], $data['roles']);
        });
        return true;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
//        $data['user_name'] = strtolower($data['user_name']);
//        if ($this['user_name'] !== $data['user_name']
//            && self::checkExist($data['user_name'])) {
//            $this->error = '用户名已存在';
//            return false;
//        }

        if ($data['phone'] != $this->phone && self::checkPhoneExist($data['phone'])) {
            $this->error = '手机号码已存在，请换一个重试！';
            return false;
        }
        if (!empty($data['password']) && ($data['password'] !== $data['password_confirm'])) {
            $this->error = '确认密码不正确';
            return false;
        }
//        if (empty($data['roles']) && !$this['is_super']) {
//            $this->error = '请选择所属角色';
//            return false;
//        }
        if (!empty($data['password'])) {
            $data['password'] = encryption_hash($data['password']);
        } else {
            unset($data['password']);
        }
        $this->transaction(function () use ($data) {
            // 更新管理员记录
            $this->save($data);
            // 更新角色关系记录
//            !$this['is_super'] && UserRole::updates((int)$this['store_user_id'], $data['roles']);
        });
        return true;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        if ($this['is_super']) {
            $this->error = '超级管理员不允许删除';
            return false;
        }
        return $this->transaction(function () {
            // 删除对应的角色关系
            UserRole::deleteAll([['store_user_id', '=', (int)$this['store_user_id']]]);
            return $this->save(['is_delete' => 1]);
        });
    }

    public function sxewm($user_id, $tb = 0)
    {
        $time = time();
        if ($user_id == -1) {
            $user_id = $this->where(['parent_store_user_id' => 0, 'is_delete' => 0])->column('store_user_id');
        }
        $this->where('store_user_id', 'in', $user_id)->save(['h5_code_time' => $time]);
        if ($tb) {
            foreach ($user_id as $item) {
                $this->sxewmss($item, $time);
            }
        }
        return true;
    }

    public function sxewmss($user_id, $time)
    {
        $list = $this->where('parent_store_user_id', '=', $user_id)->select();
        foreach ($list as $item2) {
            $this->where('store_user_id', '=', $item2->store_user_id)->save(['h5_code_time' => $time]);
            $this->sxewmss($item2->store_user_id, $time);
        }
    }

    public function ty($user_id, $status, $tb = 0)
    {
        $this->where('store_user_id', 'in', $user_id)->save(['status' => $status]);
        if ($tb) {
            foreach ($user_id as $item) {
                $this->tyss($item, $status);
            }
        }
        return true;
    }

    public function tyss($user_id, $status)
    {
        $list = $this->where('parent_store_user_id', '=', $user_id)->select();
        foreach ($list as $item2) {
            $this->where('store_user_id', '=', $item2->store_user_id)->save(['status' => $status]);
            $this->tyss($item2->store_user_id, $status);
        }
    }

    /**
     * 更新当前管理员信息
     * @param array $data
     * @return bool
     */
    public function renew(array $data)
    {
        if (!empty($data['password']) && ($data['password'] !== $data['password_confirm'])) {
            $this->error = '确认密码不正确';
            return false;
        }
        if (!empty($data['user_name']) && $this['user_name'] !== $data['user_name']
            && self::checkExist($data['user_name'])) {
            $this->error = '用户名已存在';
            return false;
        }
        !empty($data['password']) && $data['password'] = encryption_hash($data['password']);
        // 更新管理员信息
        if ($this->save($data) === false) {
            return false;
        }
        // 更新登录状态
        StoreUserService::update($this->toArray());
        return true;
    }

    public function getChildrenUserIds($userId, $data = [])
    {
        $data[] = $userId;
        $where = [
            'parent_store_user_id' => $userId,
            'is_delete' => 0,
        ];
        $cuser = $this->where($where)->select();
        if ($cuser) {
            foreach ($cuser as $v) {
                $data = array_merge($data, $this->getChildrenUserIds($v->store_user_id));
            }
            return $data;
        } else {
            return $data;
        }
    }

    public function getUserTreeList($store_user_id)
    {
        $where = [
            'store_user_id' => $store_user_id,
            'is_delete' => 0,
        ];
        $cuser = $this->where($where)->select();
        foreach ($cuser as $v) {
            $v->children = $this->getChildrenUserList($v->store_user_id);
        }
        return $cuser;
    }


}
